package shangji;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;

public class Shangji_3 {
    public static void main(String[] args) throws Exception {
        //读取XML文件,获得Document对象
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/收藏信息.xml"));
        Element rootElm = document.getRootElement();
        for (Iterator it = rootElm.elementIterator(); it.hasNext(); ) {
            Element elm = (Element) it.next();
            System.out.println(elm);
            for (Iterator iterator =elm.elementIterator();iterator.hasNext();){
                Element type = (Element) iterator.next();
                System.out.println(type);
            }
        }
        Element brandELm = rootElm.addElement("Brand");
        brandELm.addAttribute("name","三星");
        Element brandELm1 = brandELm.addElement("Type");
        brandELm1.addAttribute("name","NoteX");
        Attribute attribute = brandELm.attribute("name");
        attribute.setText("SAMSUNG");
        for (Iterator it = rootElm.elementIterator(); it.hasNext(); ) {
            Element elm = (Element) it.next();
            if (elm.getName().equals("Brand")){
            if (elm.attributeValue("name").equals("SAMSUNG")){
                rootElm.remove(elm);
                System.out.println("删除成功");
            }
        }
        }

        XMLWriter writer = new XMLWriter(new FileWriter("src/隐藏信息.xml"));
        writer.write(document);
        writer.close();
    }
}
